// 评论管理模块
const { DatabaseManager } = require('./database')
const { generateCommentData, generateReplyData, generateVoteData } = require('./random-data')

class CommentManager {
  constructor() {
    this.db = new DatabaseManager()
  }

  // 生成评论
  async generateComments(count, movieIds, userData) {
    console.log(`💬 开始生成 ${count} 条评论...`)
    
    const createdComments = []
    
    for (let i = 0; i < count; i++) {
      try {
        const movieId = movieIds[Math.floor(Math.random() * movieIds.length)]
        const user = userData[Math.floor(Math.random() * userData.length)]
        
        const commentData = generateCommentData(movieId, user.authId)
        
        const { data: comment, error } = await this.db.supabase
          .from('comments')
          .insert(commentData)
          .select()
          .single()
        
        if (error) {
          console.error(`❌ 创建评论失败:`, error)
          continue
        }
        
        createdComments.push(comment)
        console.log(`✅ 成功创建评论: ${commentData.content.substring(0, 30)}...`)
        
      } catch (error) {
        console.error(`❌ 生成评论时发生错误:`, error)
      }
    }
    
    console.log(`\n📊 评论生成完成: ${createdComments.length}/${count} 条评论`)
    return createdComments
  }

  // 生成回复评论
  async generateReplies(count, commentIds, userData) {
    console.log(`💬 开始生成 ${count} 条回复...`)
    
    const createdReplies = []
    
    for (let i = 0; i < count; i++) {
      try {
        const parentId = commentIds[Math.floor(Math.random() * commentIds.length)]
        const user = userData[Math.floor(Math.random() * userData.length)]
        
        // 获取父评论的电影ID
        const { data: parentComment, error: parentError } = await this.db.supabase
          .from('comments')
          .select('movie_id')
          .eq('id', parentId)
          .single()
        
        if (parentError || !parentComment) {
          console.error(`❌ 获取父评论失败:`, parentError)
          continue
        }
        
        const replyData = generateReplyData(parentComment.movie_id, user.authId, parentId)
        
        const { data: reply, error } = await this.db.supabase
          .from('comments')
          .insert(replyData)
          .select()
          .single()
        
        if (error) {
          console.error(`❌ 创建回复失败:`, error)
          continue
        }
        
        createdReplies.push(reply)
        console.log(`✅ 成功创建回复: ${replyData.content.substring(0, 30)}...`)
        
      } catch (error) {
        console.error(`❌ 生成回复时发生错误:`, error)
      }
    }
    
    console.log(`\n📊 回复生成完成: ${createdReplies.length}/${count} 条回复`)
    return createdReplies
  }

  // 生成评论投票
  async generateCommentVotes(commentIds, userData) {
    console.log(`👍 开始生成评论投票...`)
    
    const createdVotes = []
    
    // 为每个评论生成一些投票
    for (const commentId of commentIds) {
      try {
        // 随机选择一些用户为这个评论投票
        const voters = userData
          .sort(() => 0.5 - Math.random())
          .slice(0, Math.floor(Math.random() * 5) + 1) // 1-5个投票
        
        for (const voter of voters) {
          const voteData = generateVoteData(voter.authId, commentId)
          
          const { data: vote, error } = await this.db.supabase
            .from('comment_votes')
            .insert(voteData)
            .select()
            .single()
          
          if (error) {
            // 可能是重复投票，跳过
            continue
          }
          
          createdVotes.push(vote)
        }
        
      } catch (error) {
        console.error(`❌ 为评论 ${commentId} 生成投票时发生错误:`, error)
      }
    }
    
    console.log(`📊 投票生成完成: ${createdVotes.length} 个投票`)
    return createdVotes
  }

  // 获取评论统计信息
  async getCommentStats() {
    try {
      const { data: comments, error } = await this.db.supabase
        .from('comments')
        .select('parent_id, likes, dislikes')
      
      if (error) {
        throw error
      }
      
      const total = comments.length
      const topLevel = comments.filter(comment => !comment.parent_id).length
      const replies = total - topLevel
      const replyPercentage = total > 0 ? Math.round((replies / total) * 100) : 0
      
      const totalLikes = comments.reduce((sum, comment) => sum + parseInt(comment.likes || 0), 0)
      const totalDislikes = comments.reduce((sum, comment) => sum + parseInt(comment.dislikes || 0), 0)
      const likeDislikeRatio = totalDislikes > 0 ? (totalLikes / totalDislikes).toFixed(2) : totalLikes.toString()
      
      return {
        success: true,
        stats: {
          total,
          topLevel,
          replies,
          replyPercentage,
          totalLikes,
          totalDislikes,
          likeDislikeRatio
        }
      }
    } catch (error) {
      return { success: false, error: error.message }
    }
  }

  // 获取评论投票统计信息
  async getCommentVoteStats() {
    try {
      const { data: votes, error } = await this.db.supabase
        .from('comment_votes')
        .select('vote_type')
      
      if (error) {
        throw error
      }
      
      const total = votes.length
      const likes = votes.filter(vote => vote.vote_type === 1).length
      const dislikes = votes.filter(vote => vote.vote_type === -1).length
      
      const likePercentage = total > 0 ? Math.round((likes / total) * 100) : 0
      const dislikePercentage = total > 0 ? Math.round((dislikes / total) * 100) : 0
      
      return {
        success: true,
        stats: {
          total,
          likes,
          dislikes,
          likePercentage,
          dislikePercentage
        }
      }
    } catch (error) {
      return { success: false, error: error.message }
    }
  }

  // 清空所有评论
  async clearAllComments() {
    console.log('🗑️  开始清空所有评论...')
    
    try {
      const { error } = await this.db.supabase
        .from('comments')
        .delete()
        .neq('id', 0)
      
      if (error) {
        throw error
      }
      
      console.log('✅ 评论已清空')
      return { success: true, message: '评论已清空' }
    } catch (error) {
      console.error('❌ 清空评论时发生错误:', error)
      return { success: false, error: error.message }
    }
  }

  // 清空所有评论投票
  async clearAllVotes() {
    console.log('🗑️  开始清空所有评论投票...')
    
    try {
      const { error } = await this.db.supabase
        .from('comment_votes')
        .delete()
        .neq('id', 0)
      
      if (error) {
        throw error
      }
      
      console.log('✅ 评论投票已清空')
      return { success: true, message: '评论投票已清空' }
    } catch (error) {
      console.error('❌ 清空评论投票时发生错误:', error)
      return { success: false, error: error.message }
    }
  }
}

module.exports = CommentManager
